export default {
  props: {
    selectionConfig: {
      type: Object,
      default: () => {
        return {
          rowKey: 'id', // 数据唯一标识
          rowBoolean: true, // 是否开启翻页存下勾选数据
        };
      },
    },
    reduceHeight: { type: [String, Number], default: 265 },
  },
  data() {
    return {
      selectionData: [],
      diffSelect: [],
      tableHeight: undefined,
    };
  },
  watch: {
    height: {
      handler(v) {
        this.setFullSerrcenHeight(v);
      },
      immediate: true,
    },
  },
  methods: {
    setFullSerrcenHeight(v) {
      if (v) {
        this.tableHeight = v;
      } else {
        this.tableHeight = document.getElementById('app').scrollHeight - this.reduceHeight;
      }
    },
    handleSelectAll() {
      this.$emit('select-all');
    },
    handleSelectionChange(_val) {
      var val = this.$_.cloneDeep(_val);
      // 设置勾选，并存下数据，即使翻页保存数据
      if (this.selectionConfig.rowBoolean) {
        var _del_diff = this.$_.differenceBy(this.diffSelect, val, this.selectionConfig.rowKey);
        var choose = [...val, ..._del_diff];
        var diff = this.$_.differenceBy(this.selectionData, choose, this.selectionConfig.rowKey);
        this.selectionData = [...diff, ...val];
        this.$emit('selection-change', this.selectionData);
        this.diffSelect = val;
      } else {
        this.$emit('selection-change', val);
      }
    },
    handleSelectionclick(val, index) {
      this.handleSelectionChange([this.tableData[index]]);
      this.$set(this.tableData[index], 'check', !val.check);
    },
    // 手动设置表格中勾选项
    setCleanSelection(ary) {
      this.selectionData = ary;
      this.diffSelect = ary;
      if (ary.length > 0) {
        this.toggleRowForEarch(ary);
      } else {
        this.$refs.componentsTable.clearSelection();
      }
    },
    toggleRowForEarch(rows) {
      var idObject = this.$_.groupBy(rows, this.selectionConfig.rowKey);
      this.tableData
        .filter((f) => idObject[f.id])
        .map((row) => {
          this.toggleRowSelection(row);
        });
    },
    toggleRowSelection(row, selected = true) {
      this.$nextTick(() => {
        this.$refs.componentsTable.toggleRowSelection(row, selected);
      });
    },
  },
};
